package com.lehezn.opensource.appkit.ControlModule;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.lehezn.opensource.appkit.R;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class MeterListActivity extends GosControlModuleBaseActivity {

    private TextView tv_month_water, tv_day_water;
    private TextView tv_month_ele, tv_day_ele;
    private TextView tv_month_gos, tv_day_gos;
    private TextView tv_month_heat, tv_day_heat;

    private View lyWater, lyEle;

    private ListView listView;
    private ListviewAdapter listviewAdapter;

    private List<MeterInfo> list = new LinkedList<>(meterInfoMap.values());

    /**
     * 设备列表传入的设备变量
     */
//    private GizWifiDevice mDevice;

    private Button btnAdd;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a_main);
        initDevice();
        setActionBar(true, true, device.getAlias() == null ? "设备" : device.getAlias());
        initView();
        getStatusOfDevice();

    }

    /*
        * ========================================================================
        * 菜单栏
        * ========================================================================
        */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.more, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.more:

                Intent intent = new Intent(this, SettingActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("GizWifiDevice", device);
                intent.putExtras(bundle);
                startActivity(intent);

                break;

            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        tv_month_water = (TextView) findViewById(R.id.tv_month_water);
        tv_day_water = (TextView) findViewById(R.id.tv_day_water);

        lyWater = findViewById(R.id.ly_water);
        lyEle = findViewById(R.id.ly_ele);

        tv_month_ele = (TextView) findViewById(R.id.tv_month_e);
        tv_day_ele = (TextView) findViewById(R.id.tv_day_e);

        tv_month_gos = (TextView) findViewById(R.id.tv_month_g);
        tv_day_gos = (TextView) findViewById(R.id.tv_day_g);

        tv_month_heat = (TextView) findViewById(R.id.tv_month_h);
        tv_day_heat = (TextView) findViewById(R.id.tv_day_h);

        listView = (ListView) findViewById(R.id.listview_main);

        btnAdd = (Button) findViewById(R.id.button_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startAddActivity();
            }
        });

        list = new LinkedList<>(meterInfoMap.values());
        listviewAdapter = new ListviewAdapter(list, this);
        listView.setAdapter(listviewAdapter);
        listviewAdapter.notifyDataSetChanged();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                editDeviceActivity(list.get(i));
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                showDeleteDialog(list.get(i));
                return true;
            }
        });


    }

    private void startAddActivity() {
        Intent intent = new Intent(this, AddEleActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("GizWifiDevice", device);
        intent.putExtras(bundle);
        intent.putExtra("action", Util.ACTION_ADD);
        startActivity(intent);
//        startActivityForResult(intent, 1);


    }

    private void editDeviceActivity(MeterInfo meterInfo) {
        Intent intent = new Intent(this, EditEleActivity.class);

        Bundle bundle = new Bundle();
        bundle.putParcelable("GizWifiDevice", device);
        intent.putExtras(bundle);
        EditEleActivity.meterInfo = meterInfo;
        startActivity(intent);
//        startActivityForResult(intent, 1);


    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * Description:页面加载后弹出等待框，等待设备可被控制状态回调，如果一直不可被控，等待一段时间后自动退出界面
     */
    private void getStatusOfDevice() {
        // 设备是否可控
        if (isDeviceCanBeControlled()) {
            // 可控则查询当前设备状态
            device.getDeviceStatus();
        } else {
            // 显示等待栏
            progressDialog.show();
            if (device.isLAN()) {
                // 小循环10s未连接上设备自动退出
                mHandler.postDelayed(mRunnable, 10000);
            } else {
                // 大循环20s未连接上设备自动退出
                mHandler.postDelayed(mRunnable, 20000);
            }
        }
    }

    private Runnable mRunnable = new Runnable() {
        public void run() {
            if (isDeviceCanBeControlled()) {
                progressDialog.cancel();
            } else {
                toastDeviceNoReadyAndExit();
            }
        }

    };


    private boolean isDeviceCanBeControlled() {
        return device.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled;
    }

    private void initDevice() {
        Intent intent = getIntent();
        device = (GizWifiDevice) intent.getParcelableExtra("GizWifiDevice");
        device.setListener(gizWifiDeviceListener);
    }

    private enum handler_key {

        /**
         * 更新界面
         */
        UPDATE_UI,

        DISCONNECT,
    }


    /**
     * The handler.
     */
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handler_key key = handler_key.values()[msg.what];
            switch (key) {
                case UPDATE_UI:
                    updateUI();
                    break;
                case DISCONNECT:
                    toastDeviceDisconnectAndExit();
                    break;
            }
        }
    };


    private void toastDeviceDisconnectAndExit() {
        Toast.makeText(this, "连接已断开", Toast.LENGTH_SHORT).show();
        finish();
    }


    /**
     * Description:根据保存的的数据点的值来更新UI
     */
    protected void updateUI() {

//        Codec.decodeMeterInfo(data_meter_info, meterInfoMap);
//
//        //实时电量
//        Codec.decodeMeterRtData(data_meter_rt_data, meterInfoMap);
//        //尖峰平谷电量
//        Codec.decodeMeterForwardFum(data_meter_forward_sum, meterInfoMap);
//        //日冻结电量
//        Codec.decodeDataFreezeDay(data_data_freeze_day, meterInfoMap);
//        //月冻结电量
//        Codec.decodeDataFreezeMonth(data_data_freeze_month, meterInfoMap);

        // TODO: 17/10/8 没有水、气、热数据
        double eleMonth = 0;
        double waterMonth = 0;
        boolean hasWater = false;
        for (MeterInfo curMeter : meterInfoMap.values()) {
            if (curMeter.type == Util.TYPE_SINGLE_METER || curMeter.type == Util.TYPE_MUTIL_METER) {
                eleMonth = curMeter.getCurMonthEnery() + eleMonth;
            } else if (curMeter.type == Util.TYPE_WATER) {
                waterMonth = curMeter.getCurMonthEnery() + waterMonth;
                hasWater = true;
            }
        }
//        lyEle.setVisibility(eleMonth == 0 ? View.GONE : View.VISIBLE);//一直显示电
        if (hasWater) {
            lyWater.setVisibility(View.VISIBLE);
        } else {
            lyWater.setVisibility(View.GONE);

        }

        tv_month_ele.setText(eleMonth + "度");
        tv_month_water.setText(waterMonth + "吨");

        double eleDay = 0;
        double waterDay = 0;
        for (MeterInfo curMeter1 : meterInfoMap.values()) {
            if (curMeter1.type == Util.TYPE_SINGLE_METER || curMeter1.type == Util.TYPE_MUTIL_METER) {
                eleDay = curMeter1.getCurDayEnery() + eleDay;
            } else if (curMeter1.type == Util.TYPE_WATER) {
                waterDay = curMeter1.getCurDayEnery() + waterDay;

            }

        }
        tv_day_ele.setText(eleDay + "度");
        tv_day_water.setText(waterDay + "吨");


        list.clear();
        list.addAll(meterInfoMap.values());
        listviewAdapter.notifyDataSetChanged();

//        sw_bool_meter_rt_data.setChecked(data_meter_rt_data);
//        sw_bool_relay.setChecked(data_relay);
//        tv_data_meter_sum_Poll.setText(data_meter_sum_Poll+"");
//        sb_data_meter_sum_Poll.setProgress((int)((data_meter_sum_Poll - METER_SUM_POLL_ADDITION) / METER_SUM_POLL_RATIO - METER_SUM_POLL_OFFSET));
//        tv_data_gas_water_poll.setText(data_gas_water_poll+"");
//        sb_data_gas_water_poll.setProgress((int)((data_gas_water_poll - GAS_WATER_POLL_ADDITION) / GAS_WATER_POLL_RATIO - GAS_WATER_POLL_OFFSET));
//        tv_data_meter_interval.setText(data_meter_interval+"");
//        sb_data_meter_interval.setProgress((int)((data_meter_interval - METER_INTERVAL_ADDITION) / METER_INTERVAL_RATIO - METER_INTERVAL_OFFSET));
//        tv_data_power_change_valve.setText(data_power_change_valve+"");
//        sb_data_power_change_valve.setProgress((int)((data_power_change_valve - POWER_CHANGE_VALVE_ADDITION) / POWER_CHANGE_VALVE_RATIO - POWER_CHANGE_VALVE_OFFSET));
//        setEditText(et_extend_meter_info, HexStrUtils.bytesToHexString(data_meter_info));
//        tv_extend_meter_forward_sum.setText(HexStrUtils.splitBytesString(HexStrUtils.bytesToHexString(data_meter_forward_sum)));
//        tv_extend_meter_status.setText(HexStrUtils.splitBytesString(HexStrUtils.bytesToHexString(data_meter_status)));
//        tv_extend_data_freeze_day.setText(HexStrUtils.splitBytesString(HexStrUtils.bytesToHexString(data_data_freeze_day)));
//        tv_extend_data_freeze_month.setText(HexStrUtils.splitBytesString(HexStrUtils.bytesToHexString(data_data_freeze_month)));
        if (progressDialog.isShowing()) {

            progressDialog.cancel();
        }

    }

    private void showDeleteDialog(final MeterInfo meterInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("溫馨提示");
        builder.setMessage("确认删除？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                byte[] data = Codec.deletMeterInfo(meterInfo);
                sendJson("meter_info", data);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();

    }

    private void toastDeviceNoReadyAndExit() {
        Toast.makeText(this, "设备无响应，请检查设备是否正常工作", Toast.LENGTH_SHORT).show();
        finish();
    }

    /*
         * 设备上报数据回调，此回调包括设备主动上报数据、下发控制命令成功后设备返回ACK
         */
    @Override
    protected void didReceiveData(GizWifiErrorCode result, GizWifiDevice device,
                                  ConcurrentHashMap<String, Object> dataMap, int sn) {
        super.didReceiveData(result, device, dataMap, sn);
        Log.i("liang555666", "接收到数据");
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS && dataMap.get("data") != null) {
            getDataFromReceiveDataMap(dataMap);
            mHandler.sendEmptyMessage(handler_key.UPDATE_UI.ordinal());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        meterInfoMap.clear();
        AppData.meterInfoMap.clear();
        list.clear();
        data_data_freeze_day = null;
        data_data_freeze_month = null;
        data_meter_info = null;
        data_meter_forward_sum = null;
    }
}
